<?php
/**
 * Created by PhpStorm.
 * User: mac1
 * Date: 16/6/10
 * Time: 上午10:32
 */

namespace app\admin\controller;
use app\admin\model\Admintype;
use app\admin\model\Campus;
use app\admin\validate\AdminValidate;
use think\Db;
use app\admin\model\Admin;

class ApicircleController extends CommonController
{

    /**
     * 圈子数据
     * page
     * @return string
     */
    public function circleData(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //=============================================
        $black = Db::table('ew_black')->where('b_user_id',$user_id)->column('b_black_uid');
        if(!$black){$black = array(0);}
        //=============================================
        $field = 'circle_id,user_id,circle_content,circle_image,circle_message,circle_zan,circle_createtime,circle_url';
        $field .= ',user_username,user_image';
        $data = Db::table('ew_circle')->alias('c')
            ->join('ew_u_user uu','c.circle_user_id=uu.user_id','LEFT')
            ->where('circle_user_id','not in',$black)
            ->field($field)
            ->order('circle_createtime DESC')
            ->limit(($page-1)*10,10)
            ->select();
        $zandata = Db::table('ew_circle_zan')->where('cz_user_id',$user_id)->column('cz_circle_id');
        //===================================
        $field2 = 'u.user_id one_id,u2.user_id reply_id,u.user_username one_name,u2.user_username reply_name';
        $field2 .= ',cm_content,cm_time,u.user_image one_image,u2.user_image reply_image';
        //===================================
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['zan'] = 1;//没有点赞
                if($v['circle_image']){
                    $data[$k]['circle_image'] = explode(',',$v['circle_image']);
                }else{
                    $data[$k]['circle_image'] = array();
                }
                if($zandata){
                    if(in_array($v['circle_id'],$zandata)){
                        $data[$k]['zan'] = 2;//已经点赞
                    }
                }
                //=============================
                $circle_id = $v['circle_id'];
                $pl = Db::table('ew_circle_message')->alias('m')
                    ->join('ew_u_user u','m.cm_one_user_id=u.user_id','LEFT')
                    ->join('ew_u_user u2','m.cm_reply_user_id=u2.user_id','LEFT')
                    ->where('cm_circle_id',$circle_id)
                    ->field($field2)
                    ->select();
                $data[$k]['huifu'] = $pl;
                //=============================
            }
        }
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 单条圈子详情数据(暂时不用了，没有详情了)
     * circle_id
     * @return string
     */
    public function circleDataInfo(){
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if(!isset($share)) {
            $auth = $this->checkAll($user_id, $time, $value, $reqKey);
            if ($auth == false) {
                $returnData['status'] = 301;
                $returnData['msg'] = "Token失效！请重新登录！";
                return json_encode($returnData);
            }
        }
        $field = 'circle_id,user_id,circle_content,circle_image,circle_message,circle_zan,circle_createtime,circle_url';
        $field .= ',user_username,user_image';
        $data = Db::table('ew_circle')->alias('c')
            ->join('ew_u_user uu','c.circle_user_id=uu.user_id','LEFT')
            ->where('circle_id',$circle_id)
            ->field($field)
            ->find();
        if(!$data){
            return json_encode(['status'=>0,'msg'=>'此内容已被删除']);
        }
        if($data['circle_image']){
            $data['circle_image'] = explode(',',$data['circle_image']);
        }else{
            $data['circle_image'] = '';
        }
        $zan = Db::table('ew_circle_zan')
            ->where('cz_user_id',$user_id)
            ->where('cz_circle_id',$circle_id)
            ->find();
        if($zan){
            $data['zan'] = 2;//已经点赞
        }else{
            $data['zan'] = 1;//没有点赞
        }
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 单条圈子详情数据——评论数据
     * circle_id，page
     * @return string
     */
    public function circleDataInfoMessage(){
        header("Access-Control-Allow-Origin:*");
        extract(input());
//        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//        if($auth == false){
//            $returnData['status'] = 301;
//            $returnData['msg'] = "Token失效！请重新登录！";
//            return json_encode($returnData);
//        }
        $data = Db::table('ew_circle')
            ->where('circle_id',$circle_id)
            ->field('circle_id')
            ->find();
        if(!$data){
            return json_encode(['status'=>0,'msg'=>'此内容已被删除']);
        }
        $field = 'u.user_id one_id,u2.user_id reply_id,u.user_username one_name,u2.user_username reply_name';
        $field .= ',cm_content,cm_time,u.user_image one_image,u2.user_image reply_image';
        $field .= ',cm_zan,cm_id';
        $data = Db::table('ew_circle_message')->alias('m')
                ->join('ew_u_user u','m.cm_one_user_id=u.user_id','LEFT')
                ->join('ew_u_user u2','m.cm_reply_user_id=u2.user_id','LEFT')
                ->where('cm_circle_id',$circle_id)
                ->field($field)
                ->limit(($page-1)*10,10)
                ->select();
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['iszan'] = 0;
                $have = Db::table('ew_circle_message_zan')
                    ->where('cc_circle_message_id',$v['cm_id'])
                    ->where('cc_user_id',$user_id)
                    ->find();
                if($have){
                    $data[$k]['iszan'] = 1;
                }
            }
        }

        return json_encode(['status'=>200,'msg'=>$data]);
    }

    /**
     * 直接评论圈子的
     * @return string
     */
    public function insertCmOne(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        // 启动事务
        Db::startTrans();
        try{
            $data = array();
            $data['cm_one_user_id'] = $user_id;
            $data['cm_circle_id'] = $circle_id;
            $data['cm_content'] = $content;
            $data['cm_time'] = date('Y-m-d H:i:s');
            Db::table('ew_circle_message')->insert($data);
            //========================
            Db::table('ew_circle')
                ->where('circle_id',$circle_id)
                ->setInc('circle_message');
            //========================

            /*-----------------加入消息表------------------*/
            $notice = array();
            $notice['n_where'] = 3;
                $need = Db::table('ew_circle')->where('circle_id',$circle_id)->value('circle_user_id');
                $time = date('Y-m-d H:i:s');
            $notice['n_time'] = $time;
            $notice['n_user_id'] = $need;//给谁留言
            $notice['n_reply_user_id'] = $user_id;//谁留言
            $notice['n_circle_id'] = $circle_id;//哪个动态
            $notice['n_title'] = "在{$time}的时候给您回复了，回复内容：{$content}";
            Db::table('ew_notice')->insert($notice);
            /*----------------------end------------------*/
            // 提交事务
            Db::commit();
            /*-----------推送和透传------------*/
            $name = Db::table('ew_u_user')->where('user_id',$user_id)->value('user_username');
            $this->sendJpush("$need","{$name}回复了您的动态",array('aa'=>'bb'),1);
            /*-----------end------------*/
            return json_encode(['status'=>200,'msg'=>'成功']);
            //=====end===============
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }
    /**
     * 评论圈子的回复的回复
     * @return string
     */
    public function insertCmTwo(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        // 启动事务
        Db::startTrans();
        try{
            $data = array();
            $data['cm_one_user_id'] = $uid;
            $data['cm_reply_user_id'] = $user_id;
            $data['cm_circle_id'] = $circle_id;
            $data['cm_content'] = $content;
            $data['cm_time'] = date('Y-m-d H:i:s');
            Db::table('ew_circle_message')->insert($data);
            //========================
            Db::table('ew_circle')
                ->where('circle_id',$circle_id)
                ->setInc('circle_message');
            //========================

            /*-----------------加入消息表------------------*/
            $notice = array();
            $notice['n_where'] = 3;
            //备用：如果也需要给发布人提醒的话就两条
            //$need = Db::table('ew_circle')->where('circle_id',$circle_id)->value('circle_user_id');
            $time = date('Y-m-d H:i:s');
            $notice['n_time'] = $time;
            $notice['n_user_id'] = $uid;//给谁留言
            $notice['n_reply_user_id'] = $user_id;//谁留言
            $notice['n_circle_id'] = $circle_id;//哪个动态
            $notice['n_title'] = "在{$time}的时候给您回复了，回复内容：{$content}";
            Db::table('ew_notice')->insert($notice);
            /*----------------------end------------------*/

            // 提交事务
            Db::commit();
            /*-----------推送和透传------------*/
            $name = Db::table('ew_u_user')->where('user_id',$user_id)->value('user_username');
            $this->sendJpush("$uid","{$name}回复了您",array('aa'=>'bb'),1);
            /*-----------end------------*/
            return json_encode(['status'=>200,'msg'=>'成功']);
            //=====end===============
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }
    /**
     * 点赞或者取消点赞
     * circle_id
     * @return string
     */
    public function zanStatus(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $who = Db::table('ew_circle')->where('circle_id',$circle_id)->value('circle_user_id');
        // 启动事务
        Db::startTrans();
        try{
            $res = Db::table('ew_circle_zan')
                ->where('cz_circle_id',$circle_id)
                ->where('cz_user_id',$user_id)
                ->find();
            if($res){
                Db::table('ew_circle_zan')
                    ->where('cz_circle_id',$circle_id)
                    ->where('cz_user_id',$user_id)
                    ->delete();
                Db::table('ew_circle')
                    ->where('circle_id',$circle_id)
                    ->setDec('circle_zan');
                Db::table('ew_u_user')->where('user_id',$who)->setDec('user_zan');
            }else{
                Db::table('ew_circle_zan')
                    ->insert(['cz_circle_id'=>$circle_id,'cz_user_id'=>$user_id]);
                Db::table('ew_circle')
                    ->where('circle_id',$circle_id)
                    ->setInc('circle_zan');
                Db::table('ew_u_user')->where('user_id',$who)->setInc('user_zan');
            }
            //========================
            // 提交事务
            Db::commit();
            return json_encode(['status'=>200,'msg'=>'成功']);
            //=====end===============
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }
    /**
     * 发布动态
     * image，content
     * @return string
     */
    public function insertCircle(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $data = array();
        $data['circle_user_id'] = $user_id;
        $data['circle_content'] = $content;
        $data['circle_createtime'] = date('Y-m-d H:i:s');
        if(isset($url)){
            $data['circle_url'] = $url;
        }
        if(isset($circle_image) && $circle_image){
            $data['circle_image'] = trim($circle_image,',');
        }
        $res = Db::table('ew_circle')->insert($data);
        if($res){
            return json_encode(['status'=>200,'msg'=>'成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }
    /**
     * 发布动态时单张单张传
     * image，content
     * @return string
     */
    public function oneCircleImage(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }

        //=============更新图片==================
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if(!empty($_FILES['image']['tmp_name'])){
            $imas = array();
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$_FILES['image']['name']);
            $index = count($exe);
            $exe = $exe[$index-1];
            $_FILES['image']['name'] = $rand . '.' .$exe;
            //=======================
            if(move_uploaded_file($_FILES['image']['tmp_name'],"{$dir}/mang/image/{$_FILES['image']['name']}")){
                $url = "{$url}/mang/image/{$_FILES['image']['name']}";
                if($_FILES['image']['size'] > 1024*500) {
                    $this->image_png_size_add("$dir/mang/image/{$_FILES['image']['name']}", "$dir/mang/image/{$_FILES['image']['name']}");
                }
                return json_encode(['status'=>200,'msg'=>$url]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>'没有接收到图片']);
        }
    }



}